package cn.zahuo.SJR.jdbc.business;

import cn.zahuo.SJR.jdbc.JDBC_tools.Jdbc_tools;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
@SuppressWarnings("ALL")
public class businessMain {
    public static void main(String[] args) {
        Connection connection=null;
        PreparedStatement pstmt1=null;
        PreparedStatement pstmt2=null;

        try {
            connection = Jdbc_tools.getConnection();
//            false开启事务
            connection.setAutoCommit(false);
            String sql1="update emp set salary =salary-? where id=?";
            String sql2="update emp set salary =salary+? where id=?";
//            执行sql对象
            pstmt1=connection.prepareStatement(sql1);
            pstmt2=connection.prepareStatement(sql2);
//            设置？参数
            pstmt1.setDouble(1,500);
            pstmt1.setInt(2,1);
            pstmt2.setDouble(1,500);
            pstmt2.setInt(2,2);
//            执行sql
            pstmt1.executeUpdate();
            pstmt2.executeUpdate();

//            提交事务
            connection.commit();
        } catch (Exception throwables) {
            try {
//                抓到任何错误都将回滚
                if(connection!=null){
                    connection.rollback();
                }
            }catch (SQLException e) {
                e.printStackTrace();

            }
            throwables.printStackTrace();
        }finally {
            Jdbc_tools.close(pstmt1,connection);
//            connection第二次关闭将会产生异常
            Jdbc_tools.close(pstmt2,null);
        }
    }
}
